package com.xcity.pomelo.push.msg;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.annotation.JSONField;
import com.xcity.game.common.ItemResponse;
import com.xcity.game.item.ItemInfo;
import com.xcity.game.item.ItemService;
import com.xcity.game.item.ItemTemplate;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.push.AbstractMessagePush;

import naga.x.App;
import naga.x.game.template.TemplateService;
import naga.x.net.impl.pomelo.PomeloMessage;
import naga.x.net.impl.pomelo.protocol.Message;

@PomeloMessage(type = Message.Type.PUSH, route = PomeloRoute.PUSH_MESSAGE)
public class BatchItemsPush extends AbstractMessagePush {

	private List<ItemInfo> list;
	
	public BatchItemsPush() {
		this(10);
	}
	
	public BatchItemsPush(int capacity) {
		super(MSG_BATCH_ITEMS);
		list = new ArrayList<ItemInfo>(capacity);
	}
	
	public BatchItemsPush(int itemId, int count) {
		super(MSG_BATCH_ITEMS);
		list = new ArrayList<ItemInfo>(1);
		ItemInfo item = new ItemResponse(itemId, count);
		list.add(item);
	}
	
	public BatchItemsPush(ItemTemplate template, int count) {
		super(MSG_BATCH_ITEMS);
		list = new ArrayList<ItemInfo>(1);
		ItemInfo item = new ItemResponse(template, count);
		list.add(item);
	}
	
	public BatchItemsPush(List<ItemInfo> items) {
		super(MSG_BATCH_ITEMS);
		this.list = items;
	}

	public List<ItemInfo> getList() {
		return list;
	}

	public void setList(List<ItemInfo> list) {
		this.list = list;
	}
	
	public void add(int id, int count) {
		ItemTemplate item = App.getApp().getServiceManager().get(TemplateService.class).get(ItemTemplate.class, id);
		if (item != null) {
			add(item, count);
		}
	}
	
	public void add(ItemTemplate item, int count) {
		add(item.getId(), item.getName(), item.getIcon(), item.getDesc(), count, item.getQuality());
	}
	
	public void add(int id, String name, String icon, String desc, int count, byte quality) {
		ItemInfo item = null;
		for (int i = list.size() - 1; i >= 0; i--) {
			ItemInfo ref = list.get(i);
			if (ref.getId() == id) {
				item = ref;
				break;
			}
		}
		if (item == null) {
			item = new ItemResponse(id, 0, name, icon, desc, quality);
			list.add(item);
		}
		item.setCount(item.getCount() + count);
	}
	
	public void addGold(int val) {
		add(ItemService.goldDefault, val);
	}
	
	public void addStone(int val) {
		add(ItemService.stoneDefault, val);
	}
	
	@JSONField(serialize = false)
	public boolean isEmpty() {
		return list == null || list.isEmpty();
	}
	
}
